package com.report.bizUtil;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.report.bo.TableHeaderNode;
import com.report.bo.TableHeaderResultBo;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述:POI-tl模板表头生成
 * 功能：1.生成表头行数据2.表头合并映射
 * 参数：上下级关系的表头数据（IAS 现有的表头数据结构）
 */
public class TableHeaderUtil {
    public static void main(String[] args) {
        String a = "[{\"key\":\"1506bafa4d484d8f87c786d6ab104ae0-key\",\"label\":\"主键\",\"config\":{\"width\":150,\"type\":\"autocomplete\",\"visibleRows\":10,\"strict\":false,\"className\":\"cpas-map-model\"}},{\"key\":\"c2db33995a7b4df587d78cca50a35fec\",\"label\":\"票据种类\",\"config\":{\"width\":150,\"type\":\"text\",\"ht\":1,\"keyword\":true,\"bl\":2}},{\"key\":\"32c894e9911047869eb9fb64f656ca58\",\"label\":\"期末转应收账款金额\",\"config\":{\"width\":150,\"type\":\"numeric\",\"ht\":3,\"validator\":\"cpasFormulaValidator\",\"bl\":2}},{\"key\":\"d1a768b5972042c89a4186906edc7f43-config\",\"label\":\"rowConfig\",\"config\":{\"width\":150,\"type\":\"text\"}}]";
        JSONArray headers = JSON.parseArray(a);
        headers.remove(0);
        headers.remove(headers.size() - 1);

        TableHeaderResultBo tableHeaderResultBo = processHeader(a);
        System.out.println(JSON.toJSONString(tableHeaderResultBo));

    }

    /**
     * 处理表头
     *
     * @param header
     * @return
     */
    public static TableHeaderResultBo processHeader(String header) {
        if (StringUtils.isBlank(header)) {
            return null;
        }
        List<TableHeaderNode> tableHeaderNodes = JSON.parseArray(header, TableHeaderNode.class);

        //表头末行数据
        List<String> columns = new ArrayList<>();
        //获取表头分层数据
        Map<Integer, List<TableHeaderNode>> rowMergeIndexRange = new HashMap<>();
        AtomicInteger index = new AtomicInteger(0);
        for (TableHeaderNode node : tableHeaderNodes) {
            Integer level = 1;
            processNodeByLevel(level, index, node, columns, rowMergeIndexRange);
        }

        //生成表头数据行
        List<List<String>> list = new ArrayList<>();
        for (int i = 0; i < rowMergeIndexRange.size(); i++) {
            list.add(new ArrayList<>(columns));
        }
        //生成表头 行 合并映射
        Map<Integer, List<List<Integer>>> rowMergeMapping = new HashMap<>();
        //生成表头 列 合并映射
        Map<Integer, List<List<Integer>>> columnMergeMapping = new HashMap<>();

        //处理合并行的 列值
        for (Map.Entry<Integer, List<TableHeaderNode>> entry : rowMergeIndexRange.entrySet()) {
            //行标-1=下标
            int rowIndex = entry.getKey() - 1;
            List<String> column = list.get(rowIndex);
            entry.getValue().forEach(node -> {
                //合并区间内的label 换掉
                int startCol = node.getStartCol();
                int endCol = node.getEndCol();
                for (int i = startCol; i <= endCol; i++) {
                    column.set(i, node.getLabel());
                }
                //合并行映射
                if (startCol != endCol) {
                    rowMergeMapping.computeIfAbsent(rowIndex, k -> new ArrayList<>());
                    rowMergeMapping.computeIfPresent(rowIndex, (k, v) -> {
                        v.add(Arrays.asList(startCol, endCol));
                        return v;
                    });
                }
                //合并列映射
                if (CollectionUtil.isEmpty(node.getChildren()) && rowMergeIndexRange.size() - 1 != rowIndex) {
                    columnMergeMapping.computeIfAbsent(startCol, k -> new ArrayList<>());
                    columnMergeMapping.computeIfPresent(startCol, (k, v) -> {
                        v.add(Arrays.asList(rowIndex, rowMergeIndexRange.size() - 1));
                        return v;
                    });
                }
            });
        }
        TableHeaderResultBo tableHeaderResultBo = new TableHeaderResultBo();
        tableHeaderResultBo.setRows(list);
        tableHeaderResultBo.setRowMergeMapping(rowMergeMapping);
        tableHeaderResultBo.setColumnMergeMapping(columnMergeMapping);

        return tableHeaderResultBo;
    }

    /**
     * 处理每一行表头，合并的下标；及行列值
     *
     * @param level
     * @param atomicIndex
     * @param node
     * @param columns
     * @param levelMap
     */
    private static void processNodeByLevel(Integer level, AtomicInteger atomicIndex, TableHeaderNode node, List<String> columns, Map<Integer, List<TableHeaderNode>> levelMap) {
        // 将节点添加到对应层级
        levelMap.computeIfAbsent(level, k -> new ArrayList<>()).add(node);
        //没有子节点则为最后一行表头
        if (CollectionUtil.isEmpty(node.getChildren())) {
            int index = atomicIndex.getAndIncrement();
            node.setStartCol(index);
            node.setEndCol(index);
            node.setDepth(level);
            columns.add(node.getLabel());
        }
        // 递归处理子节点
        if (node.getChildren() != null && !node.getChildren().isEmpty()) {
            for (TableHeaderNode child : node.getChildren()) {
                processNodeByLevel(level + 1, atomicIndex, child, columns, levelMap);
            }
            node.setDepth(level);
            node.setStartCol(node.getChildren().get(0).getStartCol());
            node.setEndCol(node.getChildren().get(node.getChildren().size() - 1).getEndCol());
        }
    }
}
